################################################################################ 
#
# Counterspeech encouraging users to adopt the perspective of minority 
# groups reduces hate speech and its amplification on social media
#
# Figure 2
#
################################################################################ 


rm(list = ls())

# Set to save results
setsave = T

################################################################################ 
#  LIBRARIES  
################################################################################ 

library(dplyr)
library(ggplot2)
library(readr)
library(doBy)
library(data.table)
library(RColorBrewer)

################################################################################ 
#   DATA AND FOLDER
################################################################################ 


wd = ''
wd_res = paste0(wd, '/results')
wd_data =  paste0(wd, '/data')


data = read.csv(paste0(wd_data, '/dataset_analysis.csv'))
data = data[!(data$user_deleted == "yes"),]



################################################################################ 
#   VARIABLES
################################################################################


outvars = c('orig_tweet_deleted',
            'tox_dummy_p_key_num',
            'tox_dummy_p_key')
outvars_name = c( 'Xenophobic Tweet Deleted',
                  'No. of Xenophobic Tweets',
                  'Xenophobic Tweet Share')

treatments = c('empathy', 'traditional', 'analogical', 'getting', 'disapproval')
treatments_lab = c( 'Perspective (all)', 
                    'Traditional\nPerspective Taking',
                    'Analogical\nPerspective Taking',
                    'Perspective\nGetting', 
                    'Disapproval')

################################################################################ 
#   Scale variables
################################################################################ 

std <- function(x) sd(x, na.rm=TRUE)/sqrt(length(x))
mean <- function(x)base::mean(x, na.rm=TRUE)

################################################################################ 
#   Create Group Means and SD
################################################################################ 

temp = data[c(outvars, 'group_number', 'group_name')]
collapse_formula = as.formula(paste0(paste(outvars, collapse=' + '), '~ group_num + group_name'))

# Means
container1 = summaryBy(collapse_formula, FUN=c(mean), data=temp)
colnames(container1) = c('treat', outvars)
container1 <- melt(setDT(container1), id.vars = c("treat"), variable.name = "yvar")
colnames(container1) = c('treat', 'yvar', 'mean')

# STD
container2 = summaryBy(collapse_formula, FUN=c(std), data=temp)
colnames(container2) = c('treat', outvars)
container2 <- melt(setDT(container2), id.vars = c("treat"), variable.name = "yvar")
colnames(container2) = c('treat', 'yvar', 'sd')

# empathy
temp$group_name[temp$group_name %in% c('getting', 'traditional', 'analogical')] = 'empathy'
container3 = summaryBy(collapse_formula, FUN=c(mean), data=temp)
container3 = container3[container3$group_name=='empathy',]
colnames(container3) = c('treat', outvars)
container3 <- melt(setDT(container3), id.vars = c("treat"), variable.name = "yvar")
colnames(container3) = c('treat', 'yvar', 'mean')

# empathy
container4 = summaryBy(collapse_formula, FUN=c(std), data=temp)
container4 = container4[container4$group_name=='empathy',]
colnames(container4) = c('treat', outvars)
container4 <- melt(setDT(container4), id.vars = c("treat"), variable.name = "yvar")
colnames(container4) = c('treat', 'yvar', 'sd')
container3 = merge(container3, container4, by=c('treat', 'yvar'))

container = merge(container1, container2, by=c('treat', 'yvar'))
container = rbind(container, container3)

# titles
container$yvar_name = ''
for (var in 1:length(outvars)){
  container$yvar_name[container$yvar== outvars[var]]  = outvars_name[var]
}
container$yvar_name.f  = factor(container$yvar_name,
                                levels = outvars_name)

container$treatments_lab = 'Control'
for (var in 1:length(treatments)){
  container$treatments_lab[container$treat== treatments[var]]  = treatments_lab[var]
}
container$treatments_lab.f  = factor(container$treatments_lab,
                                     levels = c("Control","Disapproval", "Perspective (all)",
                                                "Traditional\nPerspective Taking",
                                                'Analogical\nPerspective Taking',
                                                'Perspective\nGetting'))

container$macrogroups = ''
container$macrogroups = ifelse(container$treat %in% c('control', 'empathy', 'disapproval'), 'Perspective vs Disapproval', container$macrogroups)
container$macrogroups = ifelse(container$treat %in% c('analogical', 'traditional', 'getting'), 'Perspective Treatments', container$macrogroups)
container$macrogroups.f  = factor(container$macrogroups,
                                     levels = c("Perspective vs Disapproval", "Perspective Treatments"))


################################################################################ 
#   Plot
################################################################################ 

my_colors <- RColorBrewer::brewer.pal(4, "Blues")[2:4]

ggplot(container, aes(x=macrogroups.f, y=mean, fill=treatments_lab.f)) +
  geom_bar(stat="identity", width = .8, position=position_dodge2()) +
  facet_wrap(~yvar_name.f, scales = "free") +
  geom_errorbar(aes(ymin=mean-sd*1.96, ymax=mean+sd*1.96), position=position_dodge(0.8), colour="grey", alpha=0.7, size=.5,  width = .5) +
  geom_text(aes(label=round(mean, 3)), vjust=-.3, color="black", position=position_dodge2(0.8), size=5)+
  xlab("") + ylab("") + guides(fill=guide_legend(title="")) +
  scale_fill_manual(values=c("#999999", "darkgoldenrod2",
                             'blue4', my_colors)) +
  theme_bw() +
  theme(text = element_text(size=18),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=18),
        legend.position = "bottom",
        legend.title = element_blank(),
        strip.text = element_text(size = 18)) + 
  guides(fill = guide_legend(nrow = 1))



if (setsave){ggsave(paste0(wd_res, '/figures/fig2.pdf'),  width=15, height=8)}else{print(gg1)}



